package com.egene.tw.data;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

public class UploadJobService extends Service {
    private static final String ACTION_START_UPLOAD = "start_upload";
    private boolean isUploading;//是否正在上传数据中

    public static void startUpload(Context context) {
        Intent intent = new Intent(context, UploadJobService.class);
        intent.setAction(ACTION_START_UPLOAD);
        context.startService(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && ACTION_START_UPLOAD.equals(intent.getAction())) {
            handleStartUpload();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void handleStartUpload() {
        if (isUploading) {
            return;
        }
        isUploading = true;
        DataRepository.getInstance()
                .uploadData()
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        isUploading = false;
                        stopSelf();
                    }
                })
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
